package com.globant.dao;

import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import com.globant.domain.SearchResponse;
import com.globant.domain.Tweet;
import com.globant.twittersearch.TweetContentProvider;

public class TweetDao {

	private Application service;
	
	public TweetDao(Application main) {
		service = main;
	}
	
	public void insert(SearchResponse tweets) {
		ContentValues values = new ContentValues();
		 
		for (Tweet tweet : tweets.getResults()) {
			
			values.put(Tweet.COL_DATE, tweet.getCreatedAt());
			values.put(Tweet.COL_IMAGE_URL, tweet.getProfileImageUrl());
			values.put(Tweet.COL_TWEET, tweet.getText());
			values.put(Tweet.COL_USERNAME, tweet.getFromUser());
			
			ContentResolver cr = service.getContentResolver();
			
			cr.insert(TweetContentProvider.CONTENT_URI, values);
		}
	}
	
	public List<Tweet> obtainResults() {
        String[] projection = new String[] {
        		Tweet.COL_DATE,
        		Tweet.COL_IMAGE_URL,
        		Tweet.COL_TWEET,
        		Tweet.COL_USERNAME};

        Uri tweetsUri =  TweetContentProvider.CONTENT_URI;

        ContentResolver cr = service.getContentResolver();
        
        Cursor cur = cr.query(tweetsUri,
                                 projection,
                                 null,
                                 null,
                                 null);
        
        List<Tweet> tweets = new ArrayList<Tweet>();
        
		if (cur.moveToFirst()) {            
            int colDate = cur.getColumnIndex(Tweet.COL_DATE); 
            int colImageUrl = cur.getColumnIndex(Tweet.COL_IMAGE_URL);
            int colTweet = cur.getColumnIndex(Tweet.COL_TWEET);
            int colUserName = cur.getColumnIndex(Tweet.COL_USERNAME);
            
			do {
				Tweet tweet = new Tweet();
				tweet.setCreatedAt(cur.getString(colDate));
				tweet.setFromUser(cur.getString(colUserName));
				tweet.setProfileImageUrl(cur.getString(colImageUrl));
				tweet.setText(cur.getString(colTweet));
				
				tweets.add(tweet);
            } while (cur.moveToNext());
        }
		
		return tweets;
	}
	
}
